package work.kie.haqtag2;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import work.MemberUtil;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class Setup1 {
    public static void main(String[] args) {
        EasyExcel.read(Setting.data, Item.class, getListener()).sheet().doRead();
    }

    private static ReadListener<Item> getListener() {
        return new ReadListener<Item>() {
            private AtomicInteger count = new AtomicInteger();
            private EventLoopGroup eventExecutors = new NioEventLoopGroup(32);

            private List<Item> result = new CopyOnWriteArrayList<>();

            @Override
            public void invoke(Item item, AnalysisContext analysisContext) {
                result.add(item);
                Future<String> future = eventExecutors.submit(() -> {
                    JSONArray tags = MemberUtil.findHAQTag(List.of("OT343465"), item.getThirdCode(), Setting.baseUrl, Setting.token);
                    if (CollUtil.isEmpty(tags)) {
                        return "not find";
                    }
                    JSONObject tag = tags.getJSONObject(0);
                    return validateTag(tag);
                });
                future.addListener(result -> {
                    String status = (String) result.get();
                    item.setStatus(status);
                    int number = count.getAndIncrement();
                    if (number % 1000 == 0) {
                        log.info("【tag处理】获取第{}个用户", number);
                    }
                });
            }

            @Override
            @SneakyThrows
            public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                eventExecutors.shutdownGracefully().sync();
                log.info("【tag处理】处理完毕，开始生成报表");
                EasyExcel.write(Setting.setup1, Item.class).sheet("sheet1").doWrite(result);
            }

            private static String validateTag(JSONObject tag) {
                String tagValue = tag.getStr("tagValue");
                return StrUtil.isBlank(tagValue) ? "null" : tagValue;
            }

        };


    }


}
